package app.domain;

import lombok.*;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.persistence.*;
import java.io.Serializable;
import java.util.*;

//标识实体
@Entity
//表名
@Table(name = "user")
//get set toString
@Getter
@Setter
@ToString
//有参构造
@AllArgsConstructor
//无参构造
@NoArgsConstructor
//标识当前的类会被spring boot扫描并在需要的时候创建对象
@Component
/*
 * 用户表
 */
public class User implements Serializable, UserDetails {
    //标识这个列是主键
    @Id
    //设置主键生成策略
    @GenericGenerator(name = "pk", strategy = "increment")
    //使用主键生成策略
    @GeneratedValue(generator = "pk")
    //列名
    @Column(name = "id")
    private Integer id;
    @Column(name = "username")
    private String username;
    @Column(name = "password")
    private String password;
    @Column(name = "name")
    private String name;
    @Column(name = "phone")
    private String phone;
    //时间类型
    @Temporal(TemporalType.DATE)
    @Column(name = "time")
    private Date time;
    //多对多关系 (User vs Role)
    @OneToMany(cascade = CascadeType.ALL,fetch=FetchType.EAGER)
    //@Fetch(FetchMode.SELECT)
    //中间表名,当前对象id在中间表的列名,关联的另一个表在中间表的列名
    @JoinTable(name = "ur", joinColumns = {@JoinColumn(name = "userid")}, inverseJoinColumns = {@JoinColumn(name = "roleid")})
    private Set<Role> roles;

    /**
     * 用户的权限集， 默认需要添加ROLE_ 前缀
     * 用户的加密后的密码， 不加密会使用{noop}前缀
     * 应用内唯一的用户名
     * org.springframework.security.core.userdetails.User 可以自行实现扩展以存储更多的用户信息。
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //权限集合
        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        //遍历角色
        for (Role role : getRoles()) {
            //添加查询到的角色
            grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        //返回结果
        return grantedAuthorities;
    }
    //账户是否过期
    @Override
    public boolean isAccountNonExpired() {
        return false;
    }
    //账户是否锁定
    @Override
    public boolean isAccountNonLocked() {
        return false;
    }
    //凭证是否过期
    @Override
    public boolean isCredentialsNonExpired() {
        return false;
    }
    //用户是否可用
    @Override
    public boolean isEnabled() {
        return false;
    }
}